using Arcane.Source.Client;
using Arcane.Source.Client.Extensions;
using Godot;

namespace Arcane.Source.UI
{
    [Tool]
    [GlobalClass]
    public partial class SlotFrame : Control
    {
        [Export]
        string Text { get; set; }
        [Export]
        string OverflowText { get; set; } = "...";
        [Export]
        float TextPadding { get; set; } = 1;
        private float _frameSize;
        [Export]
        float FrameSize
        {
            get => _frameSize;
            set
            {
                _frameSize = value;
                _pixelFrameSize = GetRect().Size.Y * _frameSize;
            }
        }
        [Export]
        Font font = new SystemFont();
        [Export]
        Color FrameColor { get; set; } = Colors.White;

        private float _fontSize;
        private float _pixelFrameSize;
        private TextLine _textLine;
        private bool _textDirty = true;

        public SlotFrame()
        {
            MouseFilter = MouseFilterEnum.Ignore;
            _textLine = new();
        }

        public override void _Notification(int what)
        {
            if (what == NotificationResized)
            {
                _fontSize = GetRect().Size.Y / 8.0f;
            }
        }

        public override void _Draw()
        {
            var inner = Vector2.One * _pixelFrameSize;
            DrawRect(new(0.5f * inner, GetRect().Size - inner), FrameColor, false, _pixelFrameSize);

            if (Text == null || Text.Length <= 0) return;


            var fontColor = FrameColor.GetGrayScale() > 0.5 ? Colors.Black : Colors.White;
            var fontSize = Mathf.FloorToInt(_fontSize);
            if (_textDirty)
            {
                _textLine.Clear();
                _textLine.AddString(Text, font, fontSize);
                _textDirty = false;
            }
            var textBegin = TextPadding * Vector2.Right + Vector2.Down * font.GetAscent(fontSize);
            var textSize = _textLine.GetSize();

            DrawRect(new(Vector2.Zero, 2 * TextPadding * Vector2.Right + textSize), FrameColor);
            _textLine.Draw(GetCanvasItem(), textBegin, fontColor);
        }
    }
}